/**
 * 
 */
package br.com.localfloripa.controllers;

import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.localfloripa.services.UsuarioService;

/**
 * @author alan
 * @11/03/2012
 * 
 */

@Named("usuarioController")
@RequestScoped
public class UsuarioController extends MainController {

	private static final long serialVersionUID = -5731789607223226787L;
	private static final Logger log = LoggerFactory.getLogger(UsuarioController.class);
	
	@Inject
	@Named("usuarioService")
	private UsuarioService usuarioService;
	
	private String novaSenha;

	public UsuarioController() {

	}

	public String getNovaSenha() {
		return novaSenha;
	}

	public void setNovaSenha(String novaSenha) {
		this.novaSenha = novaSenha;
	}

	/**
	 * Encaminha dados de autenticação para spring-security
	 * 
	 * @return
	 */
	public String login() {

		try {
			HttpServletRequest request = (HttpServletRequest) FacesContext
					.getCurrentInstance().getExternalContext().getRequest();
			HttpServletResponse response = (HttpServletResponse) FacesContext
					.getCurrentInstance().getExternalContext().getResponse();
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/j_spring_security_check");
			dispatcher.forward(request, response);
			FacesContext.getCurrentInstance().responseComplete();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
		return null;
	}

	/**
	 * Finaliza a sessão do usuário
	 * 
	 * @return
	 */
	public String logout() {
		try {
			HttpServletRequest request = (HttpServletRequest) FacesContext
					.getCurrentInstance().getExternalContext().getRequest();
			HttpServletResponse response = (HttpServletResponse) FacesContext
					.getCurrentInstance().getExternalContext().getResponse();
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/j_spring_security_logout");
			dispatcher.forward(request, response);
			FacesContext.getCurrentInstance().responseComplete();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
		return null;
	}

	/**
	 * Altera senha do usuário logado
	 */
	public void passwd() {

		try {
			usuarioService.passwd(getLoggedUser().getId(), novaSenha);
			this.novaSenha = "";
			
			addMessageINFO(bundle.getString("manager.security.passwd.info"));
		} catch (Exception e) {
			addMessageERROR(bundle.getString("manager.security.passwd.error"));
			log.error(e.getMessage());
		}
	}

}
